import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBC_insert_delete_update{
    public static void main(String[] args) throws SQLException {
        Scanner sc=new Scanner(System.in);
        //建立并初始化一个数据源
        DataSource dataSource=new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/demo?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("root");

        //和数据库服务器建立连接
        Connection connection=dataSource.getConnection();

        //构造sql语句
        //1.增加
        System.out.println("请输入学生姓名：");
        String name=sc.next();
        System.out.println("请输入学号：");
        int id=sc.nextInt();
        String sql="insert into student values(?,?)";
        PreparedStatement statement=connection.prepareStatement(sql);
        statement.setInt(1,id);
        statement.setString(2,name);

        //2.修改
//        System.out.println("请输入学生新的姓名：");
//        String name=sc.next();
//        System.out.println("请输入要修改学生的学号：");
//        int id=sc.nextInt();
//        String sql="update student set name=? where id=? ";
//        PreparedStatement statement=connection.prepareStatement(sql);
//        statement.setString(1,name);
//        statement.setInt(2,id);

        //3.删除
//        System.out.println("请输入要删除学生的学号：");
//        int id=sc.nextInt();
//        String sql="delete from student where id=?";
//        PreparedStatement statement=connection.prepareStatement(sql);
//        statement.setInt(1,id);

        //打印
        System.out.println(statement);
        //执行sql语句
        int ret=statement.executeUpdate();
        System.out.println("ret="+ret);

        //释放
        statement.close();
        connection.close();
    }
}






